let path = require("path")
const isPrd = process.env.NODE_ENV == "production"


const ThemeColorReplacer = require("webpack-theme-color-replacer")
const CompressionWebpackPlugin = require("compression-webpack-plugin")
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const timeStamp = new Date().getTime()

const productionGzipExtensions = ["js", "css"]

const cdn = {
  externals: { // 左侧key为项目中引入的名称，右侧value为包对外提供的名称
    vue: "Vue",
    "element-ui": "ELEMENT",
    "vue-router": "VueRouter",
    vuex: "Vuex"
  },
  css: ["//unpkg.com/element-ui@2.15.12/lib/theme-chalk/index.css"],
  js: ["//unpkg.com/vue@2.6.11/dist/vue.min.js", "//unpkg.com/vue-router@3.5.2/dist/vue-router.min.js", "//unpkg.com/vuex@3.1.2/dist/vuex.min.js", "//unpkg.com/element-ui@2.15.12/lib/index.js"]
}



module.exports = {
  devServer: {
    // open 在devServer启动且第一次构建完成时，自动用我们的系统的默认浏览器去打开要开发的网页
    open: true,
    // 默认是 localhost。如果你希望服务器外部可访问，指定如下 host: '0.0.0.0'，设置之后之后可以访问ip地址
    host: "0.0.0.0",
    port: 8080,
    // hot配置是否启用模块的热替换功能，devServer的默认行为是在发现源代码被变更后，通过自动刷新整个页面来做到事实预览，开启hot后，将在不刷新整个页面的情况下通过新模块替换老模块来做到实时预览。
    hot: true,
    https: false,
    hotOnly: false,
  },
  pluginOptions: {
    "style-resources-loader": {
      preProcessor: "less",
      patterns: [path.resolve(__dirname, "./src/theme/theme.less")]
    }
  },
  configureWebpack: (config) => {
    config.devtool = 'cheap-module-source-map'
    config.output = {
      // 输出重构  打包编译后的 文件名称  【模块名称.hash.时间戳】
      ...config.output,
      filename: `js/[hash].[name].${timeStamp}.js`,
      chunkFilename: `js/[hash].[name].${timeStamp}.js`
    }
    config.entry.app = ["babel-polyfill", "whatwg-fetch", "./src/main.js"]
    config.performance = {
      hints: false
    }
    config.plugins.push(
      new ThemeColorReplacer({
        fileName: "css/theme-colors-[contenthash:8].css",
        injectCss: true
      })
    )

    // 生产环境下将资源压缩成gzip格式
    if (isPrd) {
      // 生产环境下将资源压缩成gzip格式
      config.plugins.push(
        // 1、取消打印
        new UglifyJsPlugin({
          uglifyOptions: {
            compress: {
              drop_debugger: true,//生产环境自动删除debugger
              drop_console: true, //生产环境自动删除console
            },
            warnings: false,
          },
          sourceMap: false,   //关掉sourcemap 会生成对于调试的完整的.map文件，但同时也会减慢打包速度
          parallel: true, //使用多进程并行运行来提高构建速度。默认并发运行数：os.cpus().length - 1。
        }),

        // 2、gzip压缩
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 10240,
          minRatio: 0.8,
        })
      )
      config.externals = cdn.externals
    } else {
      config.devtool = 'cheap-module-source-map'
    }

  },
  chainWebpack: config => {
    if (!isPrd) return
    config.plugin('html').tap(args => {
      args[0].cdn = cdn
      return args
    })
  },

  css: {
    loaderOptions: {
      less: {
        lessOptions: {
          javascriptEnabled: true
        }
      }
    }
  },
  publicPath: "./",
  outputDir: "dist",
  assetsDir: "./",
  productionSourceMap: !isPrd,
}


